package com.ndhutu.ee.util.netease.nos;

import com.alibaba.fastjson.JSON;
import com.ndhutu.ee.util.DateUtil;
import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 对象存储工具类
 * @Author Shane
 * @Date 2019/8/2617:06
 * @param
 * @return
 **/
public class NOSUtil {
    /**
     * 获取上传凭证
     * @Author Shane
     * @Date 2019/8/2617:31
     * @param 
     * @return
     **/
    public static String getUploadToken(NOSConfig nosConfig, String fileName) throws Exception{
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("Bucket", nosConfig.getBucket());
        params.put("Object", fileName);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, 2);
        params.put("Expires", c.getTime().getTime()/1000);

        //进行base64编码
        String jsonStr = JSON.toJSONString(params);
        String encodedPutPolicy = new String(Base64.encodeBase64(jsonStr.getBytes()));

        //对签名字符串计算HMAC-SHA256签名
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(nosConfig.getSecretKey().getBytes(), "HmacSHA256");
        mac.init(secretKeySpec);
        String encodeSign = Base64.encodeBase64String(mac.doFinal(encodedPutPolicy.getBytes()));

        String token = "UPLOAD " + nosConfig.getAccessKey() + ":"+encodeSign + ":" + encodedPutPolicy;
        return token;
    }

    /**
     * 初始化
     * @Author Shane
     * @Date 2019/8/2618:19
     * @param
     * @return
     **/
    private static NosClient initNosClient(NOSConfig nosConfig){
        Credentials credentials = new BasicCredentials(nosConfig.getAccessKey(), nosConfig.getSecretKey());
        NosClient nosClient = new NosClient(credentials);
        nosClient.setEndpoint(nosConfig.getEndPoint());
        return nosClient;
    }

    /**
     * 上传文件
     * @Author Shane
     * @Date 2019/8/2618:19
     * @param
     * @return
     **/
    public static String uploadFile(NOSConfig nosConfig, String file) throws Exception{
        String fileName = new File(file).getName();
        String filePath = DateUtil.getCurrTimeStr("yyyy")+"/"+DateUtil.getCurrTimeStr("MM")+"/"+DateUtil.getCurrTimeStr("dd")+"/"+DateUtil.getCurrTimeStr("HHmmss");
        initNosClient(nosConfig).putObject(nosConfig.getBucket(), filePath+"/"+fileName, new File(file));
        return filePath+"/"+fileName;
    }
}
